<template>
  <div>
    <BasicModal
      v-bind="$attrs"
      :title="title"
      @register="register"
      @ok="handleSubmit"
      @cancel="handleCancel"
      :destroyOnClose="true"
      :minHeight="600"
      :width="1000"
    >
      <div class="form-container">
        <div v-for="(part, index) in tabList" :key="index" class="part-section">
          <Divider orientation="left"
            ><Tag color="processing">{{ part.propertyTeamName }}</Tag></Divider
          >
          <BasicForm
            :labelCol="{ span: 8 }"
            :wrapperCol="{ span: 16 }"
            :schemas="getSchemas(part.propertyTeamName, part.propertylst)"
            :showActionButtonGroup="false"
            @register="(form) => registerForm(form, index)"
          />
        </div>
      </div>
    </BasicModal>
  </div>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm } from '/@/components/Form';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Divider, Tag } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';

  import {
    GetBdInfoBeforeAdd,
    AddDocForm,
    OpenDocForm,
    EditDocForm,
    getBaseDetail,
  } from '/@/api/demo/document';

  const { t } = useI18n();
  const emit = defineEmits(['register', 'success']);
  const { createMessage } = useMessage();
  const title = ref('');
  const tabList = ref<any>([]);
  const activeKey = ref('');
  const SelectedDirKey = ref('');
  const FileType = ref('');
  const Type = ref('');
  const TypeName = ref('');
  const formRefs = ref<Record<string, any>>({}); // 存储每个 `BasicForm` 实例
  const FormParams = ref<any>({}); // 存储每个 `BasicForm` 实例

  // 提交表单
  const handleSubmit = async () => {
    let params = {};
    for (const key in formRefs.value) {
      params[key] = await formRefs.value[key].getFieldsValue();
    }
    FormParams.value = Object.assign({}, ...Object.values(params));
    FormParams.value = Object.entries(FormParams.value).map(([key, value]) => ({
      id: key,
      value: value,
    }));
    FormParams.value.status = filterStatus(FormParams.value.status);
    if (Type.value == '新增') {
      await AddDocForm(SelectedDirKey.value, FileType.value, FormParams.value);
      emit('success');
      handleCancel();
    } else if (Type.value == '查看') {
      await EditDocForm(TypeName.value, FormParams.value);
      emit('success');
      handleCancel();
    }
  };

  // 关闭弹窗
  const handleCancel = () => {
    tabList.value = [];
    formRefs.value = {};
    FormParams.value = {};
    closeModal();
  };

  // 辅助函数，根据不同的 propertyType 返回对应的组件类型
  function getPropertyComponent(propertyType) {
    switch (propertyType) {
      case 'varchar':
        return 'Input'; // 示例中假设 varchar 对应 Input 组件
      case 'int':
        return 'InputNumber'; // 示例中假设 int 对应 InputNumber 组件
      case 'datetime':
        return 'DatePicker'; // 示例中假设 datetime 对应 DatePicker 组件
      case 'select':
        return 'Select'; // 示例中假设 select 对应 Select 组件
      default:
        return 'Input'; // 默认使用 Input 组件
    }
  }

  // 绑定表单实例
  const registerForm = (form, key) => {
    formRefs.value[key] = form;
  };

  // 生成 schemas
  const getSchemas = (type, attributes) => {
    if (type === '基本属性') {
      return attributes.map((item) => ({
        field: item.propertyId,
        label: item.propertyName,
        component: getPropertyComponent(item.propertyType),
        defaultValue:
          getPropertyComponent(item.propertyType) === 'Select'
            ? ''
            : item.propertyId == 'status'
            ? filterStatusIn(item.defaultValue)
            : item.defaultValue,
        componentProps: {
          disabled:
            Type.value == '新增' ? filterAdd(item.propertyId) : filterUpdate(item.propertyId),
          options:
            getPropertyComponent(item.propertyType) === 'Select'
              ? item.dataSource.map((i) => ({ label: i.name, value: i.id }))
              : [],
        },
        colProps: {
          span: item.col,
        },
      }));
    } else {
      return attributes.map((item) => ({
        field: item.propertyId,
        label: item.propertyName,
        component: getPropertyComponent(item.propertyType),
        defaultValue:
          Type.value == '新增' && getPropertyComponent(item.propertyType) === 'Select'
            ? ''
            : item.defaultValue,
        componentProps: {
          required: item.pdmnull === '1',
          options:
            getPropertyComponent(item.propertyType) === 'Select'
              ? item.dataSource.map((i) => ({ label: i.name, value: i.id }))
              : [],
        },
        colProps: {
          span: item.col,
        },
      }));
    }
  };

  // label过滤新增不可操作属性
  const filterAdd = (type) => {
    const labelList = [
      'oid',
      'version',
      'creater',
      'createtime',
      'filename',
      'securitylevel',
      'status',
      'filetype',
    ];
    if (labelList.includes(type)) {
      return true;
    } else {
      return false;
    }
  };
  // label过滤修改不可操作属性
  const filterUpdate = (type) => {
    const labelList = [
      'oid',
      'ThitObjectId',
      'version',
      'creater',
      'createtime',
      'filename',
      'securitylevel',
      'status',
      'filetype',
    ];
    if (labelList.includes(type)) {
      return true;
    } else {
      return false;
    }
  };
  // 过滤状态
  const filterStatus = (type) => {
    const statusMap = {
      生效: '8',
      废止: '16',
      检出: '1',
    };
    return statusMap[type];
  };

  // 过滤状态
  const filterStatusIn = (type) => {
    const statusMap = {
      '8': '生效',
      '16': '废止',
      '1': '检出',
    };
    return statusMap[type];
  };

  // 初始化弹窗
  const [register, { setModalProps, closeModal }] = useModalInner(async (data) => {
    tabList.value = [];
    formRefs.value = {};
    FormParams.value = {};
    setModalProps({ confirmLoading: false });
    const { selectedDirKey, fileType, type, typeName } = data;
    SelectedDirKey.value = selectedDirKey;
    FileType.value = fileType;
    Type.value = type;
    TypeName.value = typeName;
    if (data.type == '新增') {
      // 根据文件类型获取表单配置
      const newRes = await getBaseDetail(FileType.value);
      tabList.value = await GetBdInfoBeforeAdd(data.fileType);
      activeKey.value = tabList.value[0].propertyTeamId;
      if (newRes.haveThitObjectId == '1') {
        // 找到 propertyTeamName 为 “基本属性” 的对象
        const team = tabList.value.find((item) => item.propertyTeamName === '基本属性');

        // 在这个对象的 propertylst 中找到 propertyId 为 "ThitObjectId" 的属性并修改
        if (team) {
          const targetProperty = team.propertylst.find(
            (prop) => prop.propertyId === 'ThitObjectId',
          );
          if (targetProperty) {
            targetProperty.defaultValue = newRes.fileQuality.thitObjectId;
          }
        }
      }
    } else if (data.type == '查看') {
      tabList.value = await OpenDocForm(data.oid, data.typeName, data.version);
      activeKey.value = tabList.value[0].propertyTeamId;
    }
  });
</script>

<style scoped></style>
